package com.wzh.yebServe.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author wzh
 * @create 2022/10/22 20:19
 * @Description: jwtToken工具类
 */
@Component
public class JwtTokenUtils {

    //用户名
    private static final String CLAIM_KEY_USERNAME = "sub";
    //荷载里面的创建时间
    private static final String CLAIM_KEY_CREATED = "created";

    //加密秘钥
    @Value("${jwt.secret}")
    private String secret;

    //过期时间
    @Value("${jwt.expiration}")
    private Long expiration;


    /**
     * 根据用户生成token
     * @param userDetails
     * @return
     */
    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims=new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME,userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }


    /**
     * 根据荷载生成token
     * @param claims
     * @return
     */
    private  String generateToken(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    /**
     * 生成token的失效效时间
     * @return
     */
    private Date generateExpirationDate() {
       return new Date(System.currentTimeMillis()+expiration*1000);
    }


    /**
     * 从荷载中获取用户名
     * @param token
     * @return
     */
    public String getUsernameFromToken(String token){
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username=claims.getSubject();
        } catch (Exception e) {
           username=null;
        }
        return  username;
    }


    /**
     * 根据token获取荷载
     * @param token
     * @return
     */

    private Claims getClaimsFromToken(String token) {
        Claims claims=null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
        }
        return  claims;
    }

    /**
     * 判断token是否过期
     * @param token
     * @return
     */
    private  boolean isTokenExpired(String token){
        Date expiredDate = getExpiredDateFromToken(token);
        return  expiredDate.before(new Date());
    }

    /**
     * 从荷载中获取过期时间
     * @param token
     * @return
     */
    private Date getExpiredDateFromToken(String token){
        Claims claims = getClaimsFromToken(token);
         return claims.getExpiration();
    }

    /**
     * 判断token是否失效
     * @param token
     * @param userDetails
     * @return
     */
    public boolean validateToken(String token,UserDetails userDetails){
        String username=getUsernameFromToken(token);
        return username.equals(userDetails.getUsername())&&!isTokenExpired(token);
    }

    /**
     * 判断token是否可以被刷新
     * @param token
     * @return
     */
    public boolean canRefresh(String token){
        return !isTokenExpired(token);
    }


    /**
     * 刷新token
     * @param token
     * @return
     */
    public String refreshToken(String token){
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }



}
